package com.itheima;

import com.itheima.domain.Student;
import com.itheima.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class annoTest {


    private StudentMapper dao;
    private SqlSession sqlSession;

    @Before
    public void init() throws Exception{
        //加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
        //获取工厂对象factory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        //获取sqlsession对象
        sqlSession=factory.openSession();
        //获取dao代理对象
        dao=sqlSession.getMapper(StudentMapper.class);

    }

    @After
    public void destroy()throws IOException{
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }



    @Test
    public void add(){
        Student stu=new Student();
        stu.setName("王文强");
        stu.setAge(17);

        //dao完成添加
        dao.add(stu);
    }

    @Test
    public void delete(){
      dao.delete(7);
    }

    @Test
    public void update(){
       Student stu=new Student();
       stu.setId(3);
       stu.setName("王五");
       stu.setAge(34);
       dao.update(stu);
    }

    @Test
    public void findAll(){
        ArrayList<Student> list = dao.findAll();
        for (Student stu : list) {
            System.out.println(stu);
        }
    }

    /*添数据并返回最后添加的id*/
    @Test
    public void addReturnId(){
        Student stu=new Student();
        stu.setName("XX");
        stu.setAge(21);

        System.out.println("保存前："+stu);
        dao.addReturnId(stu);
        System.out.println("保存后："+stu);
    }

    /*根据id查询*/
    @Test
    public void selectById(){
        Student stui=dao.selectById(9);
        System.out.println(stui);
    }

    /*模糊查询*/
    @Test
    public void selectByName(){
        List<Student> stuN=dao.selectByName("六");
        for (Student stu : stuN) {
            System.out.println(stu);
        }
    }

    /*统计查询*/
    @Test
    public void findCount(){
     Integer count=dao.findCount();
        System.out.println(count);
    }

    /*多条件查询*/
    @Test
    public void findByNameOrAge(){
        List<Student> studentList=dao.findByNameOrAge("张三",17);
        for (Student student : studentList) {
            System.out.println(student);
        }
    }

















}
